import pytest
import requests
from common.config import *
from common.yaml_util import *
from common.log_info import *

# 文件路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))





def read_data(path):
    with open(
            BASE_DIR + path, "r",
            encoding="utf-8") as f:
        json_data = json.load(f)
        return json_data


@pytest.fixture()
def get_token(env):
    clear_yaml("/data/header.yaml")
    for data in read_data("/data/account.json"):
        for i, j in data.items():
            # 获取不同节点的token
            headers_merchant = {"Content-Type": "application/json;charset=UTF-8", "application": "cms"}
            base_url = getconf(env, "zhongtai_url")
            url = base_url + "buorg/v1/session/login"
            response = requests.post(url, json=j, headers=headers_merchant)
            headers_merchant["token"] = response.json().get("token")
            write_yaml("/data/header.yaml", {f"headers_{i}": headers_merchant})


@pytest.fixture()
def get_branch_id(env):
    clear_yaml("/data/branch_id.yaml")
    # 获取节点的branchid
    headers_merchant = read_yaml("/data/header.yaml", "headers_sh")
    base_url = getconf(env, "zhongtai_url")
    url = base_url + "buorg/v1/session/userinfo"
    response = requests.get(url, headers=headers_merchant)
    write_yaml("/data/branch_id.yaml", {"tenant_id": response.json().get("data").get("tenantId")})
    write_yaml("/data/branch_id.yaml", {"sh_branch_id": response.json().get("data").get("branchId")})

    url1 = base_url + "buorg/v1/branch/branchTreeNode"
    response1 = requests.get(url1, headers=headers_merchant)
    write_yaml("/data/branch_id.yaml",
               {"yy_branch_id": response1.json().get("data").get("branchInfo")[0].get("id")})
    write_yaml("/data/branch_id.yaml",
               {"md1_branch_id": response1.json().get("data").get("branchInfo")[0].get("children")[0].get("id")})
    write_yaml("/data/branch_id.yaml",
               {"md2_branch_id": response1.json().get("data").get("branchInfo")[0].get("children")[1].get("id")})
